package top.aicey.ai.sparring.handler;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import top.aicey.ai.sparring.common.holder.SparringContext;
import top.aicey.ai.sparring.handler.dto.AgentStopEvent;
import top.aicey.ai.sparring.processor.SparringContextProcessorExecutor;
import top.aicey.ai.sparring.service.DelayAIAgentInstanceService;
import top.aicey.ai.sparring.service.ISceneInstanceEvaluationService;


@Component
@Slf4j
public class AgentStopEventHandler {

    @Autowired
    private SparringContextProcessorExecutor sparringContextProcessorExecutor;

    @Autowired
    private ISceneInstanceEvaluationService sceneInstanceEvaluationService;


    @Autowired
    private DelayAIAgentInstanceService delayAIAgentInstanceService;

    @EventListener(AgentStopEvent.class)
    public void onEvent(AgentStopEvent event){
        log.info("handler event start:{}", JSON.toJSONString(event));
        String instanceId = event.getInstanceId();

        SparringContext context = sparringContextProcessorExecutor.get(event.getInstanceId());
        log.info("Agent stop event context:{}",context);
        if (Objects.isNull(context)){
            log.info("Agent stop event does not exist!instanceId:{}",instanceId);
            return;
        }
        // 异常终止情况下 直接生成报告

        // 初始化评价
        boolean initialized = sceneInstanceEvaluationService.initBySparringContext(context);
        if (!initialized){
            // 已经存在了  则不再处理
            return;
        }

        delayAIAgentInstanceService.delayStopAIAgentInstance(context.getAiAgentInstanceId());

        sparringContextProcessorExecutor.clear(instanceId);
        log.info("handler event end!");
    }
}
